package com.xiuxia.bopicturebackend.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.xiuxia.bopicturebackend.annotation.CheckAuth;
import com.xiuxia.bopicturebackend.common.BaseResponse;
import com.xiuxia.bopicturebackend.common.MinIOUtil;
import com.xiuxia.bopicturebackend.common.ResultUtils;
import com.xiuxia.bopicturebackend.config.CosClientConfig;
import com.xiuxia.bopicturebackend.config.MinioConfig;
import com.xiuxia.bopicturebackend.constant.UserConstant;
import com.xiuxia.bopicturebackend.exception.BusinessException;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.manager.CosManager;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "fileController")
public class FileController {
    @Resource
    private CosManager cosManager;
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private UserService userService;
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private MinIOUtil minIOUtil;

    /**
     * 用户上传头像接口
     *
     * @param multipartFile 文件
     * @param request       请求
     * @return 头像地址
     */
    @PostMapping("/upload/userAvatar")
    @ApiOperation("用户上传头像接口")
    public BaseResponse<String> UploadUserAvatar(@RequestPart("file") MultipartFile multipartFile, HttpServletRequest request) {
        String fileName = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        User loginUser = userService.getLoginUser(request);

        // 获取旧头像路径
        String oldAvatarUrl = loginUser.getUserAvatar();
        if (StrUtil.isNotEmpty(oldAvatarUrl)) {
            String replace = oldAvatarUrl.replace(cosClientConfig.getHost(), "");
            cosManager.deleteObject(replace);
        }

        fileName = String.format("%s.%s",
                uuid, (StrUtil.isEmpty(FileUtil.getSuffix(fileName)) ? "webp" : FileUtil.getSuffix(fileName)));
        String filePath = String.format("/userAvatar/%s/%s", loginUser.getId(), fileName);
        File file = null;
        try {
            file = File.createTempFile(fileName, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            return ResultUtils.success(cosClientConfig.getHost() + "/" + filePath);
        } catch (Exception e) {
            log.error("file upload error , file path = {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, file path = {}", filePath);
                }
            }
        }
    }

    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    @ApiOperation("测试下载文件接口")
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInputStream = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInputStream = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error , file path = {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInputStream != null) {
                cosObjectInputStream.close();
            }
        }

    }
}
